package com.example.demo.util;

import com.example.demo.context.CurrentOperator;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 *@Description token工具
 *@Author Levi
 *@Date 2019/4/23-17:47
*/
public class JWTUtil {
    private static final Key KEY = new SecretKeySpec("token".getBytes(), SignatureAlgorithm.HS512.getJcaName());

    /**
     * 生成token
     */
    public static String getToken(Long operatorId, String username){
        String subject = operatorId.toString() + "," + username;
        return Jwts.builder().setSubject(subject).signWith(SignatureAlgorithm.HS512, KEY).compact()+"@"+System.currentTimeMillis();
    }

    /**
     * 解析token
     */
    public static CurrentOperator parseToken(String token){
        token = token.split("@")[0];
        String subject = null;
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(KEY)
                    .parseClaimsJws(token).getBody();
            subject = claims.getSubject();
        } catch (Exception e) {
        }
        String[] str =subject.split(",");
        CurrentOperator currentOperator = new CurrentOperator();
        currentOperator.setId(Long.parseLong(str[0]));
        currentOperator.setUsername(str[1]);
        return currentOperator;
    }
}
